import { NextRequest, NextResponse } from 'next/server'
import { updateTool, getTools } from '@/lib/database'
import { requireAdmin, withErrorHandling } from '@/lib/auth-middleware'

export const PATCH = withErrorHandling(async (request: NextRequest, context: any) => {
  return requireAdmin(request, async (req) => {
    // 从URL中提取ID
    const url = new URL(request.url)
    const pathSegments = url.pathname.split('/')
    const id = pathSegments[pathSegments.length - 2] // toggle前面的ID

    const body = await request.json()
    const { isDeployed } = body

    console.log(`管理员 ${req.user?.name} 切换工具 ${id} 状态为: ${isDeployed ? '上线' : '下线'}`)

    // 获取工具信息
    const tools = await getTools(request)
    const tool = tools.find(t => t.id === id)

    if (!tool) {
      return NextResponse.json(
        { error: '工具不存在' },
        { status: 404 }
      )
    }

    // 判断是否为外部工具
    const isExternal = !tool.deployPath || tool.deployPath.trim() === ''

    // 更新工具状态
    await updateTool(id, {
      isDeployed,
      updatedAt: new Date().toISOString()
    })

    const message = isExternal
      ? `外部工具${isDeployed ? '已上线' : '已下线'}`
      : `工具${isDeployed ? '部署' : '下线'}成功`

    return NextResponse.json({
      success: true,
      message,
      isExternal
    })

  })
})
